<template>
  <el-dialog
      title="提示"
      :visible.sync="isShow"
      width="35%"

  >
    <el-transfer v-model="value" :data="categorys" :titles="['可选分类', '已选分类']" style="margin-left: 30px"></el-transfer>
    <span slot="footer" class="dialog-footer">
    <el-button @click="isShow = false">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { listCategory } from '@/api/category'
import { getBindCategorys } from '@/api/mainBudget'

export default {
  name: 'MainCategory',
  props: ['mainBudgetId'],
  watch: {
    'mainBudgetId':{
      handler(newVal) {
        if (Number.isInteger(newVal)) {
          if (this.mainBudgetId) {
            getBindCategorys(this.mainBudgetId).then(n => {
              this.value = n.map(n => n.id)
            })
          }
        } else {
          this.value=[]
        }
      }
    }
  },
  data() {
    return {
      isShow: false,
      categorys: [],
      categoryMap: new Map(),
      value: []
    }
  },
  methods: {
    save() {
      this.$emit('addCategory',this.value.map(n=>{
        return {
          id:n,
          name: this.categoryMap.get(n).name,
          description: this.categoryMap.get(n).description
        }
      }))
      this.isShow = false
    }
  },
  mounted() {

    //分类源数据
    listCategory().then(data => {
      data.forEach(n=>{
        this.categoryMap.set(n.id, {
          name: n.name,
          description:n.description
        })
      })
      this.categorys = data.map(n => {
        return {
          key: n.id,
          label: n.name
        }
      })
    })

    this.$bus.$on('handleCategoryAdd', () => {
      this.isShow = true
    })
  }
}
</script>

<style scoped>

</style>
